//
// UploadResponder
//
// Copyright (C) jextra.net.
//
//  This file is part of the Nubbin Library.
//
//  The Nubbin Library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  The Nubbin Library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with the Nubbin Library; if not, write to the Free
//  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
//  02111-1307 USA.
//

package net.jextra.nubbinstoreweb;

import com.javapepper.core.*;
import com.javapepper.util.*;
import java.io.*;
import javax.servlet.http.*;

public class UploadResponder extends BaseResponder
{
    // ============================================================
    // Fields
    // ============================================================

    public static final int BUFFER_SIZE = 50000;

    // ============================================================
    // Methods
    // ============================================================

    // ----------
    // public
    // ----------

    @Override
    public void processRequest( PepSession pepSession, PepMethod method, HttpServletRequest request,
        HttpServletResponse response )
        throws Exception
    {
        if ( method == PepMethod.GET )
        {
            throw new RuntimeException( "HTTP GET not supported." );
        }

        System.out.println( "UploadResponder" );
        PepParameters params = new PepParameters( request );
        StorePathMapper pathMap = new StorePathMapper( request );
        File file = getStore().getFile( pathMap.getComponentName(), pathMap.getVersionNumber(),
            pathMap.getPath() );

        file.getParentFile().mkdirs();
        // Just get the first file, that is all that is supported.
        PepFileParameter fileParam = params.getFileParameters( "file" ).get( 0 );
        FileOutputStream out = new FileOutputStream( file );
        InputStream in = new FileInputStream( fileParam.getFile() );
        byte[] buf = new byte[BUFFER_SIZE];
        int i = 0;
        while ( ( i = in.read( buf ) ) != -1 )
        {
            out.write( buf, 0, i );
        }
        in.close();
        out.close();
    }
}

